/*** 
 * @Author: pengcheng
 * @Date: 2021-06-24 10:27:50
 * @LastEditTime: 2021-09-18 10:08:18
 * @LastEditors: pengcheng
 * @Description: 
 * @FilePath: /kylin-daq/src/LogRecord.cpp
 */
#include "LogRecord.h"

QScopedPointer<LogRecord> LogRecord::ms_instance;

LogRecord::LogRecord(QObject *parent):QObject(parent)
, m_setDate(QDate::currentDate())
{
    m_startTimeMsec = QDateTime::currentMSecsSinceEpoch();
    m_logDirPath = QDir::rootPath() + s_logBaseFolderPath; 
    qInstallMessageHandler(qtMessageHandler);
}

LogRecord::~LogRecord()
{

}

LogRecord *LogRecord::instance(void)
{
    if (ms_instance.isNull()) {
        ms_instance.reset(new LogRecord);
    }
    return ms_instance.data();
}

void LogRecord::qtMessageHandler(QtMsgType type,
                                 const QMessageLogContext &context,
                                 const QString &message)
{
    QString outMsg;
    QString level;
    QString funcInfo;
    switch (type) {
    case QtDebugMsg:
#ifndef DEBUG
    return;
#endif
    level = "D";
    break;
    case QtInfoMsg:
    level = "I";
    break;
    case QtWarningMsg:
    level = "W";
    break;
    case QtCriticalMsg:
    level = "C";
    break;
    case QtFatalMsg:
    level = "F";
    break;
    }
    funcInfo = context.file ? QString("-%1:%2(%3)|").arg(context.file).arg(context.line).arg(context.function) : "|";
    outMsg = QString("|%1 | %2 %3").arg(level).arg(funcInfo).arg(message);
    instance()->record(outMsg);
}

void LogRecord::record(const QString &message)
{
    QMutexLocker mutexLocker(&m_writeFileMutexLock);
    setDate();
    QDir dir(m_logDirPath);
    QFile logFile(m_logFilePath);
    QString nowDateTimeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss,zzz");
    qint64 diffTimeMsec = QDateTime::currentMSecsSinceEpoch() - m_startTimeMsec;
    Qt::HANDLE threadId = QThread::currentThreadId();
    QString writedMessage = QString("%1 (%2) [%3] %4\n").arg(nowDateTimeStr).arg(diffTimeMsec).arg(quintptr(threadId)).arg(message);
    if(!dir.exists()) {
        if(!dir.mkpath(m_logDirPath))
        {
            return;
        }
    }
    if (!logFile.open(QIODevice::Append | QIODevice::WriteOnly | QIODevice::Text))
    {
        return;
    }
    logFile.write(writedMessage.toUtf8());
    logFile.close();
}

void LogRecord::doInit(const QString &strAppName)
{
    m_appName = strAppName.toLower();
    m_appName.replace(QRegExp("[^a-z0-9]"), "-");
    m_appName.replace(QRegExp("[-]+"), "-");
    m_appName.replace(QRegExp("^[^a-z]+"), "");
    m_appName.replace(QRegExp("[-]+$"), "");
    atexit(shutdown);
}

void LogRecord::shutdown()
{
    if(instance()->m_logFile.isOpen())
    {
        instance()->m_logFile.close();
    }
}

void LogRecord::init(const QString &strAppName)
{
    return instance()->doInit(strAppName);
}

void LogRecord::setDate()
{
    // 检查是否同一天
    QDate nowDate(QDate::currentDate());
    if (m_logFilePath == "") {
        m_logFilePath = QString("%1%2-%3.log").arg(m_logDirPath, m_appName, m_setDate.toString("yyyy-MM-dd"));
    }
    if (m_setDate != nowDate) {
        m_setDate = nowDate;
        m_logFilePath = QString("%1%2-%3.log").arg(m_logDirPath, m_appName, m_setDate.toString("yyyy-MM-dd"));
    }
}
